/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.service.impl;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.seari.bean.User;
import com.seari.bean.UserRole;
import com.seari.dto.CheckAuthRequest;
import com.seari.dto.CheckAuthResponse;
import com.seari.exception.ExceptionUtil;
import com.seari.exception.ServiceException;
import com.seari.exception.ValidateException;
import com.seari.mapper.UserMapper;
import com.seari.mapper.UserRoleMapper;
import com.seari.pojo.QueryUser;
import com.seari.service.UserService;
import com.seari.user.constants.ResponseCodeEnum;
import com.seari.utils.JwtTokenUtils;
import com.seari.utils.JwtUtil;

/**
 *
 * @author Rainbow
 */
@Service("userService")
public class UserServiceImpl implements UserService
{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    Logger Log=LoggerFactory.getLogger(this.getClass());

    @Override
    public int getUserByLogin(String username, String password, String stationName)
    {
        return userMapper.getUserByLogin(username, password, stationName);
    }


    @Override
    public List<User> getUserByUid(QueryUser qu){
    	return userMapper.getUserByUid(qu);
    }
    @Override
    public List<User> getUserByParams(QueryUser qu)
    {
        return userMapper.getUserByParams(qu);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addUser(User user)
    {
        return userMapper.addUser(user);
    }

    @Override
    public int checkUserExist(QueryUser qu)
    {
        return userMapper.checkUserExist(qu);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(User user)
    {
         userMapper.updateUser(user);
         userRoleMapper.deleteUserRoleByUuid(user.getUid());
         UserRole userRole = new UserRole();
         userRole.setUuid(user.getUid().intValue());
         userRole.setUurid(user.getUrids());
         return userRoleMapper.apportionRoles(userRole);
          
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUser(int uid)
    {
    	userRoleMapper.deleteUserRoleByUuid((long)uid);
    	//System.out.println(1 / 0);
        return userMapper.deleteUser(uid);
    }

	@Override
	public int getUserListCount(QueryUser qu) {
		return userMapper.getUserListCount(qu);
	}

	@Override
	public CheckAuthResponse validToken(CheckAuthRequest request) {
		CheckAuthResponse response = new CheckAuthResponse();
    	try{
    		beforeValidateAuth(request);
    		String token = request.getToken();
    		System.out.println(token);
    		String parseJWT = JwtUtil.parseJWT(token).toString();
    		System.out.println(parseJWT);
    		Claims claims = JwtTokenUtils.phaseToken(token);
    		response.setUid(claims.get("uid").toString());
    		response.setCode(ResponseCodeEnum.SUCCESS.getCode());
    		response.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
    	}catch (ExpiredJwtException e){
            Log.error("Expire :"+e);
            response.setCode(ResponseCodeEnum.TOKEN_EXPIRE.getCode());
            response.setMsg(ResponseCodeEnum.TOKEN_EXPIRE.getMsg());
        }catch (SignatureException e1){
            Log.error("SignatureException :"+e1);
            response.setCode(ResponseCodeEnum.SIGNATURE_ERROR.getCode());
            response.setMsg(ResponseCodeEnum.SIGNATURE_ERROR.getMsg());
        }catch (Exception e){
            Log.error("login occur exception :"+e);
            ServiceException serviceException=(ServiceException) ExceptionUtil.handlerException4biz(e);
            response.setCode(serviceException.getErrorCode());
            response.setMsg(serviceException.getErrorMessage());
        }finally{
    		Log.info("reponse:"+response);
    	}
    	
    	
    	return response;
	}
	
	private void beforeValidateAuth(CheckAuthRequest request){
        if(request==null){
            throw new ValidateException("请求对象为空");
        }
        if(StringUtils.isEmpty(request.getToken())){
            throw new ValidateException("token信息为空");
        }
    }

	@Override
	public List<User> userSearch(QueryUser qu) {
		// TODO Auto-generated method stub
		return userMapper.userSearch(qu);
	}


	@Override
	public List<Integer> getRoleIdByUid(QueryUser qu) {
		// TODO Auto-generated method stub
		return userMapper.getRoleIdByUid(qu);
	}


	@Override
	public List<String> getStationNamesByLine(String stationLine) {
		// TODO Auto-generated method stub
		return userMapper.getStationNamesByLine(stationLine);
	}



    
}
